package org.bud.rung.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.bud.rung.netty.coder.Decoder;
import org.bud.rung.netty.coder.Encoder;

/**
 * @author shaun
 * @date 2024/8/10
 * @instruction
 */
public class NettyServer {
    private static final NettyServer INSTANCE = new NettyServer();
    private NettyServer(){}

    public void start(){
        Thread serverDaemon = new Thread(){
            @Override
            public void run() {
                EventLoopGroup boss = new NioEventLoopGroup();
                EventLoopGroup worker = new NioEventLoopGroup();
                ServerBootstrap bootstrap = new ServerBootstrap();
                try {
                    ChannelFuture sync = bootstrap
                            .group(boss, worker)
                            .channel(NioServerSocketChannel.class)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) throws Exception {
                                    ch.pipeline()
                                            .addLast(new Decoder())
                                            .addLast(new Encoder())
                                            .addLast(new ServerInHandler());
                                }
                            })
                            .bind(9996)
                            .sync();
                } catch (InterruptedException e) {
                    this.interrupt();
                }
            }
        };
        serverDaemon.setDaemon(true);
        serverDaemon.start();

    }

    public static NettyServer getInstance(){
        return INSTANCE;
    }

}
